#!/bin/bash

#
# bak -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# "Backups" a given file or list of files by creating a compressed copy with
# incremental number
#

#
# Functions
#

# Main function
function Main() {

  if [ "$1" == "" ]; then
    echo "Usage: bak <file1> [<file2> [<file3>...]]"
    exit 1
  fi

  local FN
  local COUNT

  # Loop over all the given files
  while [ $# -gt 0 ]; do

    FN="$1"
    COUNT=0

    while :
    do

      FMT=`printf '%s.%05u.bz2' "$FN" $COUNT`

      if [ ! -e "$FMT" ]; then
        echo -n "Backupping $FN to $FMT..."
        bzip2 -c "$FN" > "$FMT" 2> /dev/null
        if [ $? == 0 ]; then
          echo " done!"
        else
          rm -f "$FMT" > /dev/null 2> /dev/null
          echo " FAILED!"
        fi
        break
      fi

      let COUNT++

    done

    shift
  done
}

#
# Entry point
#

Main "$@"
